<template>
  <div class="user-role">
    <div class="action-bar">
      <h3>角色管理</h3>
      <el-button type="primary" @click="openAddRoleDialog">
        <el-icon><Plus /></el-icon>
        添加角色
      </el-button>
    </div>
    
    <el-table :data="roles" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" width="150" />
      <el-table-column prop="code" label="角色代码" width="150" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="permissions" label="权限" width="200">
        <template #default="{ row }">
          <el-tag v-for="perm in row.permissions" :key="perm" size="small" style="margin-right: 4px;">
            {{ perm }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userCount" label="用户数" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="openEditRoleDialog(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="text" size="small" @click="confirmDeleteRole(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
          <el-button type="text" size="small" @click="openAssignUsersDialog(row)">
            <el-icon><User /></el-icon>
            添加用户
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑 角色对话框 -->
    <el-dialog :title="dialogTitle" v-model="roleDialogVisible" width="520px" :close-on-click-modal="false">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="96px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="例如：管理员" />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" placeholder="例如：admin（唯一）" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="角色说明" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-select v-model="roleForm.permissions" multiple placeholder="选择权限" style="width: 100%;">
            <el-option v-for="p in allPermissions" :key="p" :label="p" :value="p" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio-button label="active">启用</el-radio-button>
            <el-radio-button label="disabled">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitRole">保 存</el-button>
      </template>
    </el-dialog>

    <!-- 为角色添加用户对话框 -->
    <el-dialog :title="`为【${currentRole?.name || ''}】添加用户`" v-model="assignDialogVisible" width="720px" :close-on-click-modal="false">
      <div style="margin-bottom: 12px; display: flex; gap: 8px; align-items: center;">
        <el-input v-model="userSearch.username" placeholder="按用户名搜索" clearable style="width: 200px;" @keyup.enter="fetchUsers" />
        <el-input v-model="userSearch.email" placeholder="按邮箱搜索" clearable style="width: 200px;" @keyup.enter="fetchUsers" />
        <el-input v-model="userSearch.phone" placeholder="按手机号搜索" clearable style="width: 200px;" @keyup.enter="fetchUsers" />
        <el-button type="primary" @click="fetchUsers"><el-icon><Search /></el-icon>搜索</el-button>
        <el-button @click="resetUserSearch"><el-icon><Refresh /></el-icon>重置</el-button>
      </div>
      <el-table :data="userList" v-loading="userLoading" @selection-change="onUserSelectionChange" height="360">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="160" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="type" label="角色" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ getRoleLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">{{ row.status === 1 ? '正常' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div style="display:flex; justify-content:flex-end; margin-top: 12px;">
        <el-pagination
          v-model:current-page="userPage.current"
          v-model:page-size="userPage.size"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userPage.total"
          @size-change="fetchUsers"
          @current-change="fetchUsers"
        />
      </div>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="selectedUserIds.length === 0" :loading="assignLoading" @click="submitAssignUsers">添 加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/plugins/axios'

export default {
  name: 'UserRole',
  setup() {
    const loading = ref(false)
    const roles = ref([
      {
        id: 1,
        name: '超级管理员',
        code: 'super_admin',
        description: '拥有系统所有权限',
        permissions: ['用户管理', '角色管理', '系统配置', '数据管理'],
        userCount: 1,
        status: 'active'
      },
      {
        id: 2,
        name: '管理员',
        code: 'admin',
        description: '拥有大部分管理权限',
        permissions: ['用户管理', '数据管理', '报告管理'],
        userCount: 3,
        status: 'active'
      },
      {
        id: 3,
        name: '普通用户',
        code: 'user',
        description: '基础功能使用权限',
        permissions: ['数据查看', '报告查看'],
        userCount: 1250,
        status: 'active'
      }
    ])

    const allPermissions = ref(['用户管理', '角色管理', '系统配置', '数据管理', '数据分析', '报告管理'])

    // 获取角色列表（若后端无此接口，将保持本地示例数据）
    const fetchRoles = async () => {
      loading.value = true
      try {
        const resp = await axios.post('/role/list', {}, { params: { pageNum: 1, pageSize: 200 } })
        if (resp?.data?.code === 1) {
          const records = resp.data.data.records || []
          roles.value = records.map(r => ({
            id: r.id,
            name: r.name,
            code: r.code,
            description: r.description,
            permissions: r.permissions || [],
            userCount: r.userCount ?? 0,
            status: r.status === 1 || r.status === 'active' ? 'active' : 'disabled'
          }))
        }
      } catch (e) {
        // 忽略错误，使用本地示例数据
      } finally {
        loading.value = false
      }
    }

    onMounted(() => fetchRoles())

    // 新增/编辑 角色
    const roleDialogVisible = ref(false)
    const dialogMode = ref('add') // 'add' | 'edit'
    const submitLoading = ref(false)
    const roleFormRef = ref(null)
    const roleForm = reactive({
      id: undefined,
      name: '',
      code: '',
      description: '',
      permissions: [],
      status: 'active'
    })
    const roleRules = {
      name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      code: [{ required: true, message: '请输入角色代码', trigger: 'blur' }],
      permissions: [{ type: 'array', required: true, message: '请选择权限', trigger: 'change' }]
    }
    const dialogTitle = computed(() => (dialogMode.value === 'add' ? '添加角色' : '编辑角色'))

    const resetRoleForm = () => {
      roleForm.id = undefined
      roleForm.name = ''
      roleForm.code = ''
      roleForm.description = ''
      roleForm.permissions = []
      roleForm.status = 'active'
    }

    const openAddRoleDialog = () => {
      dialogMode.value = 'add'
      resetRoleForm()
      roleDialogVisible.value = true
    }

    const openEditRoleDialog = (role) => {
      dialogMode.value = 'edit'
      roleForm.id = role.id
      roleForm.name = role.name
      roleForm.code = role.code
      roleForm.description = role.description
      roleForm.permissions = Array.isArray(role.permissions) ? [...role.permissions] : []
      roleForm.status = role.status
      roleDialogVisible.value = true
    }

    const upsertLocalRole = () => {
      if (dialogMode.value === 'add') {
        const newId = Math.max(0, ...roles.value.map(r => r.id || 0)) + 1
        roles.value.unshift({
          id: newId,
          name: roleForm.name,
          code: roleForm.code,
          description: roleForm.description,
          permissions: [...roleForm.permissions],
          userCount: 0,
          status: roleForm.status
        })
      } else {
        const idx = roles.value.findIndex(r => r.id === roleForm.id)
        if (idx !== -1) {
          roles.value[idx] = {
            ...roles.value[idx],
            name: roleForm.name,
            code: roleForm.code,
            description: roleForm.description,
            permissions: [...roleForm.permissions],
            status: roleForm.status
          }
        }
      }
    }

    const submitRole = () => {
      roleFormRef.value?.validate(async (valid) => {
        if (!valid) return
        submitLoading.value = true
        try {
          if (dialogMode.value === 'add') {
            const resp = await axios.post('/role/add', {
              name: roleForm.name,
              code: roleForm.code,
              description: roleForm.description,
              permissions: roleForm.permissions,
              status: roleForm.status === 'active' ? 1 : 0
            })
            if (resp?.data?.code === 1) {
              ElMessage.success('添加成功')
              await fetchRoles()
              roleDialogVisible.value = false
              return
            }
          } else {
            const resp = await axios.post('/role/update', {
              id: roleForm.id,
              name: roleForm.name,
              code: roleForm.code,
              description: roleForm.description,
              permissions: roleForm.permissions,
              status: roleForm.status === 'active' ? 1 : 0
            })
            if (resp?.data?.code === 1) {
              ElMessage.success('保存成功')
              await fetchRoles()
              roleDialogVisible.value = false
              return
            }
          }
          // 如果后端未实现，走本地回退
          upsertLocalRole()
          ElMessage.success('已保存（本地）')
          roleDialogVisible.value = false
        } catch (e) {
          // 本地回退
          upsertLocalRole()
          ElMessage.success('已保存（本地）')
          roleDialogVisible.value = false
        } finally {
          submitLoading.value = false
        }
      })
    }

    // 兼容多环境的安全确认方法
    const safeConfirm = (message, title, options) => {
      try {
        if (typeof ElMessageBox !== 'undefined' && ElMessageBox && typeof ElMessageBox.confirm === 'function') {
          return ElMessageBox.confirm(message, title, options)
        }
      } catch (e) { /* ignore */ }
      const app = getCurrentInstance()?.appContext?.config?.globalProperties
      if (app && typeof app.$confirm === 'function') {
        return app.$confirm(message, title, options)
      }
      if (typeof window !== 'undefined' && typeof window.confirm === 'function') {
        return window.confirm(message) ? Promise.resolve() : Promise.reject(new Error('cancel'))
      }
      return Promise.reject(new Error('confirm unavailable'))
    }

    const confirmDeleteRole = (role) => {
      safeConfirm(
        `确定要删除角色 "${role.name}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const resp = await axios.post(`/role/delete/${role.id}`)
          if (resp?.data?.code === 1) {
            ElMessage.success('删除成功')
            await fetchRoles()
            return
          }
        } catch (e) {
          // ignore and fallback
        }
        const index = roles.value.findIndex(r => r.id === role.id)
        if (index !== -1) {
          roles.value.splice(index, 1)
          ElMessage.success('删除成功（本地）')
        }
      }).catch(() => {})
    }

    // 为角色添加用户
    const assignDialogVisible = ref(false)
    const currentRole = ref(null)
    const userLoading = ref(false)
    const userList = ref([])
    const selectedUserIds = ref([])
    const assignLoading = ref(false)
    const userSearch = reactive({ username: '', email: '', phone: '' })
    const userPage = reactive({ current: 1, size: 10, total: 0 })

    const getRoleLabel = (type) => {
      if (typeof type === 'number') {
        return { 0: '超级管理员', 1: '管理员', 2: '普通用户' }[type] || '未知'
      }
      return { super_admin: '超级管理员', admin: '管理员', user: '普通用户' }[type] || '未知'
    }

    const fetchUsers = async () => {
      userLoading.value = true
      try {
        const params = { pageNum: userPage.current, pageSize: userPage.size }
        const searchData = {}
        Object.keys(userSearch).forEach(k => {
          if (userSearch[k]) searchData[k] = userSearch[k]
        })
        const resp = await axios.post('/user/list', searchData, { params })
        if (resp?.data?.code === 1) {
          userList.value = resp.data.data.records || []
          userPage.total = resp.data.data.total || 0
        }
      } catch (e) {
        // ignore
      } finally {
        userLoading.value = false
      }
    }

    const resetUserSearch = () => {
      userSearch.username = ''
      userSearch.email = ''
      userSearch.phone = ''
      userPage.current = 1
      fetchUsers()
    }

    const onUserSelectionChange = (selection) => {
      selectedUserIds.value = selection.map(s => s.id)
    }

    const openAssignUsersDialog = (role) => {
      currentRole.value = role
      selectedUserIds.value = []
      assignDialogVisible.value = true
      userPage.current = 1
      fetchUsers()
    }

    const submitAssignUsers = async () => {
      if (!currentRole.value) return
      assignLoading.value = true
      try {
        const resp = await axios.post('/role/assignUsers', {
          roleId: currentRole.value.id,
          userIds: selectedUserIds.value
        })
        if (resp?.data?.code === 1) {
          ElMessage.success('添加成功')
          currentRole.value.userCount = (currentRole.value.userCount || 0) + selectedUserIds.value.length
          assignDialogVisible.value = false
          return
        }
      } catch (e) {
        // ignore and fallback
      } finally {
        assignLoading.value = false
      }
      // 本地回退
      currentRole.value.userCount = (currentRole.value.userCount || 0) + selectedUserIds.value.length
      ElMessage.success('添加成功（本地）')
      assignDialogVisible.value = false
    }

    return {
      // 列表
      loading,
      roles,
      allPermissions,
      fetchRoles,

      // 新增/编辑
      roleDialogVisible,
      dialogMode,
      dialogTitle,
      roleForm,
      roleRules,
      roleFormRef,
      submitLoading,
      openAddRoleDialog,
      openEditRoleDialog,
      submitRole,
      confirmDeleteRole,

      // 添加用户到角色
      assignDialogVisible,
      currentRole,
      userSearch,
      userList,
      userPage,
      userLoading,
      selectedUserIds,
      openAssignUsersDialog,
      fetchUsers,
      resetUserSearch,
      onUserSelectionChange,
      submitAssignUsers,

      // util
      getRoleLabel
    }
  }
}
</script>

<style scoped>
.user-role {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.action-bar h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}
</style>
